import request from "@/utils/request";

const FileAPI = {
  /**
   * 上传文件
   */
  upload(data: FormData) {
    return request<any, FileInfo>({
      url: "/api/v1/files",
      method: "post",
      data: data,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },
  getById(id?: string) {
    return request<any, FileInfo>({
      url: `/api/v1/files/${id}`,
      method: "get",
    });
  },
  /**
   * 上传文件
   */
  uploadFile(file: File) {
    const formData = new FormData();
    formData.append("file", file);
    return request<any, FileInfo>({
      url: "/api/v1/files",
      method: "post",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },

  preview(fileId?: string) {
    return request<any, string>({
      url: `/api/v1/files/url/${fileId}`,
      method: "get",
    });
  },

  /**
   * 下载文件
   * @param url
   * @param fileName
   */
  download(id?: string, fileName?: string) {
    return request({
      url: `/api/v1/files/download/${id}`,
      method: "get",
      responseType: "blob",
    }).then((res) => {
      const blob = new Blob([res.data]);
      const a = document.createElement("a");
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = fileName || "下载文件";
      a.click();
      window.URL.revokeObjectURL(url);
    });
  },
};

export default FileAPI;

/**
 * 文件对象
 */
export interface FileInfo {
  /**
   * 主键
   */
  id?: string;

  name?: string;

  /**
   * 附件名称 (原始文件名)
   */
  fileName?: string;

  /**
   * 附件类型 (MIME类型)
   */
  contentType?: string;

  /**
   * 附件大小 (字节)
   */
  fileSize?: number;

  /**
   * 存储目录
   */
  folder?: string;

  /**
   * Minio存储的文件名
   */
  minioFileName?: string;

  /**
   * 文件后缀 (如 .pdf, .docx)
   */
  suffix?: string;
}
